<template>
  <div class="bg-lightColor notice-con p-3 rounded" v-if="editModel === 'view'">
    <n-grid
      x-gap="12"
      :cols="1"
      class="mb-2"
      v-permission="[PERMISSIONS.ADMIN_SETTING]"
    >
      <n-gi>
        <n-button
          type="primary"
          size="small"
          class="!text-[13px]"
          @click="handleToAdd"
        >
          <SvgIcon
            icon="zengjiatianjiajiahao"
            color="#badeff"
            class="mr-1"
          ></SvgIcon>
          新增
        </n-button>
      </n-gi>
    </n-grid>
    <wp-data-table
      v-loading="loading"
      :data="data"
      :checked-row-keys="checkedRowKeys"
      :columns="columns"
      @page-change="handlePageChange"
      @select-change="handleSelectChange"
      @order-change="handleOrderChange"
      :pages="pageResultInfo.pages"
      :total="pageResultInfo.total"
    >
    </wp-data-table>
  </div>

  <!-- 添加或者更新面板 -->
  <create-and-update-notice
    :is-modify="editModel === 'update'"
    :notice-res="curNotice"
    v-else
    @back-view="editModel = 'view'"
    @change-notice="handleAddAndUpdateNotice"
  ></create-and-update-notice>

  <!-- 通知的panel -->
  <MyDialog
    default-width="35%"
    default-height="90%"
    v-if="dialogs.notice"
    @close="dialogs.notice = false"
  >
    <template #title>
      <div class="flex items-center text-[#555] text-[13px]">
        <SvgIcon icon="icon_notice" class="mr-1"></SvgIcon>
        通知
      </div>
    </template>
    <NoticePanel
      :title="curNotice!.name"
      :content="curNotice!.content"
      :time="curNotice!.createTime"
    ></NoticePanel>
  </MyDialog>
</template>

<script setup lang="ts">
import { useMessage, NButton, useDialog } from 'naive-ui'
import { NSwitch } from 'naive-ui'
import type { DataTableColumns } from 'naive-ui'
import {
  getNoticeByPage,
  updateNotice,
  createNotice,
  delNotice,
  sortNotice
} from '@/api/notice'
import type {
  NoticeCreateReq,
  NoticeRes,
  NoticeRowData,
  NoticeUpdateReq
} from '@/types/notice'
import { PERMISSIONS } from '@/constants/permission'
import { formatTime } from '@/utils/index'
import { load } from '@/utils/loading'
import { renderSort } from '@/utils/commonBusiness'
import SvgIcon from '@/components/SvgIcon/index.vue'
import WpDataTable from '@/components/WpDataTable/index.vue'
import CreateAndUpdateNotice from './components/CreateAndUpdateNotice.vue'
import NoticePanel from '@/views/User/Explorer/components/NoticePanel.vue'

const message = useMessage()
const dialog = useDialog()

const data = ref<NoticeRowData[]>([])
const pageInfo = reactive({
  page: 1,
  pageSize: 50
})

const pageResultInfo = reactive({
  pages: 0,
  total: 0
})

const loading = ref(false)

const createColumns = (): DataTableColumns<NoticeRowData> => {
  return [
    {
      type: 'selection',
      minWidth: 30,
      width: 30
    },
    {
      title: '名称',
      key: 'name',
      minWidth: 120,
      width: 120,
      render: (row) => {
        return renderSort(() => `${row.name}`)
      }
    },
    {
      title: '状态',
      minWidth: 120,
      width: 120,
      key: 'sendTime',
      render(row) {
        return h(
          NTag,
          {
            style: {
              fontSize: '13px'
            },
            type: new Date(row.sendTime) > new Date() ? 'warning' : 'success',
            bordered: false
          },
          {
            default: () =>
              new Date(row.sendTime) > new Date() ? '等待推送' : '已推送'
          }
        )
      }
    },
    {
      title: '推送时间',
      key: 'sendTime',
      minWidth: 150,
      width: 150,
      render(row) {
        return formatTime(row.sendTime)
      }
    },
    {
      title: '创建时间',
      key: 'createTime',
      minWidth: 150,
      width: 150,
      render(row) {
        return formatTime(row.createTime)
      }
    },
    {
      title: '是否启用',
      key: 'isActive',
      minWidth: 120,
      width: 120,
      render(row) {
        return h(NSwitch, {
          value: row.isActive === 1,
          onUpdateValue: (value: boolean) => handleActiveNotice(row, value)
        })
      }
    },
    {
      title: '操作',
      key: 'actions',
      minWidth: 150,
      width: 150,
      render(row) {
        return h('div', [
          h(
            NButton,
            {
              text: true,
              type: 'primary',
              size: 'small',
              class: 'text-[13px]',
              onClick: () => handleToUpdate(row)
            },
            { default: () => '编辑' }
          ),
          h(
            NButton,
            {
              text: true,
              type: 'primary',
              size: 'small',
              class: 'ml-2 text-[13px]',
              onClick: () => handleToPreview(row)
            },
            { default: () => '预览' }
          ),
          h(
            NButton,
            {
              text: true,
              type: 'primary',
              size: 'small',
              class: 'ml-2 text-[13px]',
              onClick: () => handleToDel(row)
            },
            { default: () => '删除' }
          )
        ])
      }
    }
  ]
}

const checkedRowKeys = ref<string[]>([])

const columns = createColumns()

// 获取通知列表
const loadNotices = () => {
  loading.value = true
  getNoticeByPage(pageInfo)
    .then((res) => {
      data.value = res.data.items
      pageResultInfo.pages = res.data.pages
      pageResultInfo.total = res.data.total
    })
    .catch(console.error)
    .finally(() => {
      loading.value = false
    })
}

onMounted(() => {
  loadNotices()
})

const handlePageChange = (page?: number, pageSize?: number) => {
  page && (pageInfo.page = page)
  pageSize && (pageInfo.pageSize = pageSize)
  loadNotices()
}

const handleSelectChange = (rows: string[]) => {
  checkedRowKeys.value = rows.map((item) => item)
}

// 启用或者禁用通知
const handleActiveNotice = (row: NoticeRowData, value: boolean) => {
  row.isActive = value ? 1 : 0
  load.show()
  updateNotice({
    noticeId: row.id,
    name: row.name,
    content: row.content,
    auth: JSON.parse(row.auth as any),
    type: row.type,
    level: row.level,
    isActive: row.isActive,
    sendTime: row.sendTime
  })
    .then(() => {
      message.success('操作成功')
    })
    .catch(console.error)
    .finally(() => {
      load.hide()
    })
}

// 去添加通知
const handleToAdd = () => {
  editModel.value = 'create'
}

const curNotice = ref<NoticeRes>()
// 去编辑通知
const handleToUpdate = (row: NoticeRowData) => {
  curNotice.value = row
  editModel.value = 'update'
}

const dialogs = reactive({
  notice: false
})
// const curNotice=ref<any>()
// 去预览通知
const handleToPreview = (row: NoticeRowData) => {
  curNotice.value = row
  dialogs.notice = true
}

// 去删除通知
const handleToDel = (row: NoticeRowData) => {
  dialog.warning({
    title: '提示',
    content: '你确定要删除该通知吗？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      load.show()
      delNotice([row.id])
        .then(() => {
          message.success('删除通知成功')
          afterOpt()
        })
        .catch(console.error)
        .finally(() => {
          load.hide()
        })
    },
    onNegativeClick: () => {}
  })
}

// ================================= 通知新增和更新逻辑===============================================
const editModel = ref<'create' | 'update' | 'view'>('view')

const handleAddNotice = (data: NoticeCreateReq) => {
  load.show()
  createNotice(data)
    .then(() => {
      message.success('添加通知成功')
      afterOpt()
    })
    .catch(console.error)
    .finally(() => {
      load.hide()
    })
}

const handleUpdateNotice = (data: NoticeUpdateReq) => {
  load.show()
  updateNotice(data)
    .then(() => {
      message.success('更新通知成功')
      afterOpt()
    })
    .catch(console.error)
    .finally(() => {
      load.hide()
    })
}

const handleAddAndUpdateNotice = (type: number, data: NoticeUpdateReq) => {
  if (type === 1) {
    handleUpdateNotice(data as NoticeUpdateReq)
  } else {
    handleAddNotice(data)
  }
}

const handleOrderChange = (newIndex: number, oldIndex: number) => {
  // 当前的顺序
  const ids = data.value.map((item) => item.id)
  const res = ids.splice(oldIndex, 1)
  ids.splice(newIndex, 0, ...res)
  sortNotice(ids)
    .then(() => {
      afterOpt()
    })
    .catch(console.error)
}

const afterOpt = () => {
  loadNotices()
  editModel.value = 'view'
}
</script>

<style scoped lang="scss">
.notice-con {
  font-size: 13px;

  :deep(.n-data-table-tbody .n-data-table-tr:hover .n-data-table-td) {
    background-color: #e5f3ff;

    .move {
      opacity: 0.85;
    }
  }

  :deep(.my-handle) {
    height: 28px;
    line-height: 28px;
    // height: calc(100% + 16px);
    position: relative;
    .move {
      transition: all 0.3s var(--n-bezier);
      opacity: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #d1ecfa;
      color: $primaryColor;
      position: absolute !important;
      left: -8px;
      top: -8px;
      bottom: -8px;
      width: 40px;
      // right: 0;
      cursor: move;
    }
  }
}
</style>
